package com.chb.test;

import com.chb.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Test;

import java.io.IOException;

public class FilterDemo {
    RestHighLevelClient client = ESClient.getClient();
    String index = "sms-logs-index";

    @Test
    public  void height() throws IOException {
        // 1、SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        // 2、指定查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 2.1、查询条件
        searchSourceBuilder.query(QueryBuilders.matchQuery("smsContent", "魅力"));
        // 2.2、指定高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("smsContent", 10)
                .preTags("<font color='red'>")
                .postTags("</font>");

        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);

        // 3、执行
        SearchResponse resp = client.search(searchRequest, RequestOptions.DEFAULT);

        // 4、打印
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getHighlightFields().get("smsContent"));
        }
    }

    @Test
    public void filterQuery() throws IOException {
        // 1、SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        // 2、指定查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.termQuery("smsContent", "魅力"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("fee").lte(400));

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        // 3、执行
        SearchResponse resp = client.search(searchRequest, RequestOptions.DEFAULT);

        // 4、打印
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
